package com.bosc.modeling.service;

import com.bosc.modeling.dao.gen.CompetitionEntityMapper;
import com.bosc.modeling.dao.gen.EnrollEntityMapper;
import com.bosc.modeling.pojo.gen.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CompetitionService {
    @Autowired
    CompetitionEntityMapper competitionEntityMapper;
    @Autowired
    EnrollEntityMapper enrollEntityMapper;
    public List<CompetitionEntity> getCompetitionList(){
        CompetitionEntityExample example = new CompetitionEntityExample();
        example.setOrderByClause("create_time desc");
        List<CompetitionEntity> competitions = competitionEntityMapper.selectByExample(example);
        for (int i = 0; i < competitions.size(); i++) {
            CompetitionEntity competition = competitions.get(i);
            long joins = getJoins(competition.getCompetitionId());
            competition.setJoins((int)joins);
        }
        return competitions;
    }
    public int delCompetition(int id){
        return competitionEntityMapper.deleteByPrimaryKey(id);

    }
    public long getJoins(String competitionId){
        EnrollEntityExample example = new EnrollEntityExample();
        example.createCriteria().andCompetitionIdEqualTo(competitionId);
        return enrollEntityMapper.countByExample(example);
    }

    public CompetitionEntity getCompetition(int id){
        return competitionEntityMapper.selectByPrimaryKey(id);

    }
    public List<CompetitionEntity> getCompetitionById(String competitionId){
        CompetitionEntityExample example = new CompetitionEntityExample();
        example.createCriteria().andCompetitionIdEqualTo(competitionId);
        return competitionEntityMapper.selectByExample(example);

    }
    public List<CompetitionEntity> searchCompetition(String name){
        CompetitionEntityExample example = new CompetitionEntityExample();
        example.createCriteria().andCompetitionNameLike("%"+name+"%");
        example.setOrderByClause("create_time desc");
        return competitionEntityMapper.selectByExample(example);

    }
    public int addCompetition(CompetitionEntity competition){
        return competitionEntityMapper.insertSelective(competition);

    }
    public int updateCompetition(CompetitionEntity competition){
        return competitionEntityMapper.updateByPrimaryKeySelective(competition);
    }
}
